package com.ck.controller.student;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.ck.domain.Panduan;
import com.ck.domain.Tiankong;
import com.ck.service.QuestionService;

public class ExerciseTiankongController extends AbstractController {

	private QuestionService questionService;

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Integer TIANKONG_NUM = 5;	//题目数量.必须与QuestionServiceImpl.gainTiankongForExercise()中的一致.
		Map model = new HashMap();
		
		Integer correct_count = 0;
		List<Tiankong> tiankongList = new ArrayList<Tiankong>();
		
		for(int i=0; i<TIANKONG_NUM; i++){
			//获取题目并记住题目的顺序
			Integer tiankongID = Integer.parseInt(request.getParameter("tiankongID_"+i));
			Tiankong tiankong = questionService.gainTiankong(tiankongID);
			
			//获取用户选择的答案
			String user_answer = request.getParameter("user_answer_"+i);

			//批改答案
			if( user_answer == null || "".equals(user_answer)){
				tiankong.setUser_answer(null);
				tiankong.setAnswer_result(0);
			}else{
				tiankong.setUser_answer(user_answer);
				
				boolean flag = false;
				//检查用户的答案是否与正确答案匹配.
				if( user_answer.equals(tiankong.getCorrect_answer()) ){
					flag = true;
				}
				
				//检查用户的答案是否与近义词答案1匹配.
				if( (tiankong.getSynonym_one() != null) && user_answer.equals(tiankong.getSynonym_one()) ){
					flag = true;
				}
				
				//检查用户的答案是否与近义词答案2匹配.
				if( (tiankong.getSynonym_two() != null) && user_answer.equals(tiankong.getSynonym_two()) ){
					flag = true;
				}
				
				//检查用户的答案是否与近义词答案3匹配.
				if( (tiankong.getSynonym_three() != null) && user_answer.equals(tiankong.getSynonym_three()) ){
					flag = true;
				}
				
				if( flag ){
					tiankong.setAnswer_result(1);
					correct_count++;
				}else{
					tiankong.setAnswer_result(0);
				}
			}

			tiankongList.add(tiankong);
		}
		
		model.put("tiankongList", tiankongList);
		model.put("correct_count", correct_count);
		model.put("tiankong_num", TIANKONG_NUM);
		
		//把组卷参数也传回页面
		Integer chapterID = Integer.parseInt(request.getParameter("chapterID"));
		Integer difficulty = Integer.parseInt(request.getParameter("difficulty"));
		String chapterName = questionService.gainChapter(chapterID).getName();
		
		model.put("chapterID", chapterID);
		model.put("difficulty", difficulty);
		model.put("chapterName", chapterName);
		
		return new ModelAndView("student/exerciseTiankong", model);
	}

}
